package com.buyi.easyhome.util

import android.content.Context
import android.speech.tts.TextToSpeech
import android.util.Log
import java.util.Locale

class TTSHelper(context: Context) {
    private var tts: TextToSpeech? = null
    var isInitialized = false
    var isInitSuccess = false

    companion object {
        private const val TAG = "TTSHelper"

        @Volatile
        private var INSTANCE: TTSHelper? = null

        fun getInstance(context: Context): TTSHelper {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: TTSHelper(context).also { INSTANCE = it }
            }
        }

        fun destroy() {
            INSTANCE?.destroy()
        }
    }

    init {
        tts = TextToSpeech(context) { status ->
            isInitialized = true
            if (status == TextToSpeech.SUCCESS) {
                Log.d(TAG, "TTSHelper: tts init success!")
                isInitSuccess = true
                tts?.language = Locale.getDefault()
                tts?.setSpeechRate(1.2f)
            } else {
                Log.e(TAG, "TTSHelper: tts init failed!")
                isInitSuccess = false
            }
        }
    }

    fun playText(textToSpeechText: String, queueMode: Int = TextToSpeech.QUEUE_FLUSH) {
        if (isInitSuccess) {
            tts?.speak(textToSpeechText, queueMode, null, "tts")
        }
    }

    // 播放拨号键盘的音频
    fun playDialpadTone(char: Char) {
        // 获取要播报的文本
        val textToSpeak = when (char) {
            '*' -> "星号"
            '#' -> "井号"
            else -> char.toString()
        }

        // 使用已有的 TTSHelper 播报
        playText(textToSpeak, queueMode = TextToSpeech.QUEUE_ADD)
    }

    fun stopSpeak() {
        tts?.stop()
    }

    fun destroy() {
        tts?.run {
            stop()
            shutdown()
        }
        tts = null
        isInitialized = false
        isInitSuccess = false
        INSTANCE = null
        Log.d(TAG, "destroy: TTS destroy success!")
    }
}
